import dly from '@/components/release.vue'
import linkCard from '@/components/linkCard.vue'
import {
  getAuthLinks
} from './authLinks.js'

export default {
  components: {
    dly,
    linkCard,
  },
  data() {
    return {
      list: [],
      auth: '', // 权限
      storeListShow: false,
      // 默认公司店铺
      store: {
        storeId: 1,
        storeName: '达州森垚荣威4S',
        companyName: '四川7迈车汽车销售服务有限公司',
        isPay: false
      },
      user: null, // 个人信息
      // 企业店铺列表
      storeList: [{
        storeId: 1,
        storeName: '达州森垚荣威4S',
        companyName: '四川7迈车汽车销售服务有限公司',
      }, ],

      // 根据权限获取不同显示的内容
      contentLinks: null,

      // 功能选项列表
      modulesList: [{
        path: '/pages_common/pages_me/assets/assetsManage/assetsManage',
        icon: 'iconzichanguanli',
        label: '资产管理',
        color: '#fed82a',
      },
      {
        path: '/pages_common/pages_me/company/company',
        icon: 'iconqiye1',
        label: '我的企业',
        color: '#fed82a',
      },
      // 暂时隐藏
      // {
      //   path: '#',
      //   icon: 'iconshiyongshouce',
      //   label: '使用手册',
      //   color: '#fed82a',
      // },
      {
        path: '/pages_common/pages_me/setting/setting',
        icon: 'iconshezhi',
        label: '设置',
        color: '#fed82a',
      },
        // 暂时隐藏
        // {
        //   path: '#',
        //   icon: 'iconfapiao1',
        //   label: '我的发票',
        //   color: '#fed82a',
        // },
      ],
    }
  },

  computed: {
    //是否支付保证金
    isPay() {
      let show = false
      if (this.$store.state.userInfoDetail.store) {
        show = this.$store.state.userInfoDetail.store.isPay || false
      }
      return show
    },
  },

  onLoad() {
    this.getStoreList()
    this.LoginChooseStore()
  },
  onShow(){
    this.store=uni.getStorageSync('userInfoDetail').store
    this.user = uni.getStorageSync('userInfoDetail').user
    console.log('第一次进onShow', this.store)
  },
  created() {
    this.handleAuthContent()
  },
  onHide() {
    this.storeListShow = false
  },
  methods: {
    async LoginChooseStore() {
		  try {
		    let data = {
		      'pageIndex': 1,
		      'pageSize': 100,
		      'mobile': uni.getStorageSync('Ztc_B_USER_INFO').mobile
		    }
		    const res = await this.$api.user.LoginChooseStore(data)
		    console.log(res)
		    this.list = res.data.list

		  } catch (e) {
		    console.log(e)
		    //TODO handle the exception
		  }
    },
    // 处理权限显示的内容
    handleAuthContent() {
      // 获取权限和企业店铺信息
      this.auth = uni.getStorageSync('Ztc_B_USER_INFO').permious
      this.store = uni.getStorageSync('userInfoDetail').store
      this.user = uni.getStorageSync('userInfoDetail').user
      // this.auth = 'RepairStore'
      this.contentLinks = getAuthLinks(this.auth)
    },
    // 进入公司
    async EnterCompany(item,index) {
      console.log(item)
			 this.clicktrue=true
			 uni.showLoading({
			 	title: '正在切换店铺'
			 })
		  let role = ''
		  if (this.list[index].role === 0) {
		    role = '员工'
		  } else if (this.list[index].role === 1) {
		    role = '管理员'
		  } else if (this.list[index].role === 2) {
		    role = '超级管理员'
		  }
		  let store = {
		    companyName: this.list[index].companyname,
		    storeId: this.list[index].store_id,
		    storeName: this.list[index].store_name,
		    isPay: this.list[index].deposit_balance > 0 ? true : false
		  }
		  let user = {
		    headImg: this.list[index].headportrait,
		    jobName: this.list[index].job,
		    roleName: role,
		    userName: this.list[index].truename
		  }
		  try {
		    const res = await this.$api.store.SwitchStoreInfo({
		      Storeid: this.list[index].store_id,
		    })
		    // 储存用户登录基本信息
		    uni.setStorageSync('Ztc_B_USER_INFO', res.data)
		    uni.setStorageSync('token', res.data.token)
		  } catch (err) {
		    console.log(err)
		  }
		  let userInfo = this.$store.state.userInfoDetail
		  userInfo.store = store
		  user.isPWD=userInfo.user.isPWD
		  user.login=userInfo.user.login
		  userInfo.user = user
		  uni.setStorageSync('userInfoDetail', userInfo)
		  this.$store.commit('setUserInfoDetail', userInfo)

		  let userMsg = this.$store.state.user.userInfo
		  userMsg.tid = this.list[index].accountid
		  userMsg.permious = this.list[index].permious
		  userMsg.merchant_type=this.list[index].merchant_type
		  userMsg.examine_status=this.list[index].examine_status
		  userMsg.role = this.list[index].role
		  this.$store.commit('user/setUserInfo', userMsg)
		  this.$store.commit('setUserInfo', userMsg)
		  //用户信息存储
		  uni.setStorage({
		    key: 'Ztc_B_USER_INFO',
		    data: userMsg,
		  })
		  console.log(this.$store.state)
		  uni.reLaunch({
		    url: '/pages/index/index',
		  })
		  uni.hideLoading()
    },
    // 获取店铺列表
    async getStoreList() {
      try {
        const res = await this.$api.store.GetStoreList({
          PageIndex: 1,
          PageSize: 100,
        })
        console.log('店铺列表', res)
        let storeId = this.store.storeId
        // 店铺列表
        this.storeList = res.data.list.filter(
          item => item.storeId !== storeId
        )
        // 当前店铺
        this.store = res.data.list.find(
          item => item.storeId === storeId
        )
        let userInfo= uni.getStorageSync('userInfoDetail')
        userInfo.store=this.store
        uni.setStorageSync('userInfoDetail',userInfo)
      } catch (err) {
        console.log(err)
      }
    },

    // 切换店铺
    async switchStoreInfo(item) {
      this.storeListShow = !this.storeListShow
      uni.showLoading({
        title: '正在切换店铺',
      })
      try {
        const res = await this.$api.store.SwitchStoreInfo({
          Storeid: item.storeId,
        })
        console.log('switch店铺', res)
        // 储存用户登录基本信息
        uni.setStorageSync('Ztc_B_USER_INFO', res.data)
        uni.setStorageSync('token', res.data.token)
        this.$store.commit('user/setUserInfo', res.data)
        this.$store.commit('setUserInfo', res.data)
        this.getUserInfo()
      } catch (err) {
        console.log(err)
      }
      uni.hideLoading()
    },

    // 切换店铺完成后，获取用户信息
    async getUserInfo() {
      try {
        const res = await this.$api.user.getUserInfo()
        // 储存用户详细信息
        uni.setStorageSync('userInfoDetail', res.data)
        this.$store.commit('setUserInfoDetail', res.data)

        this.handleAuthContent()  // 处理权限显示的内容
        // 重新获取店铺列表
        this.getStoreList()
        // 退出tim的登录
        this.timSignOut()
        uni.switchTab({
				  url: '/pages/index/index'
        })
      } catch (e) {
        //TODO handle the exception
      }
    },

    // 退出tim登录
    timSignOut() {
      this.tim.logout()
        .then(res => {
          this.$store.commit('news/reset')

          // 获取tim信息
          this.getTimInfo()
        })
        .catch(err => {
          console.log('退出失败')
        })
    },

    // 获取tim信息
    getTimInfo() {
      this.$api.news
        .getTimInfo({
          storeId: this.$store.state.userInfoDetail.store.storeId,
        })
        .then(res => {
          this.$store.commit('news/setUer', {
            userId: res.data.userid,
            user: res.data.username !== null
              ? res.data.username : this.$store.state.userInfoDetail.store.storeName,
            img: res.data.img,
            userSig: res.data.usersig,
          })
          this.timLogin()
        })
    },

    // 登录tim
    timLogin() {
      console.log('登录tim:', this.$store.state.news.userId)
      this.tim
        .login({
          userID: this.$store.state.news.userId,
          userSig: this.$store.state.news.userSig,
        })
        .then(res => {
          //登录成功后 更新登录状态
          this.$store.commit('news/toggleIsLogin', true)
          //tim 返回的用户信息
          // uni.setStorageSync('userTIMInfo', JSON.stringify(res.data))
          // this.$store.commit('createConversationActive', item.Tid)
        })
        .catch(err => {
          console.warn('login error:', err) // 登录失败的相关信息
        })
    },

    // 企业店铺列表下拉显示
    storeListDown() {
      this.storeListShow = !this.storeListShow
    },

    // 点击遮罩层，收起企业店铺列表
    clickMask() {
      this.storeListShow = false
    },
    // 个人信息
    goUserInfo() {
      this.user.meFlag = true
      let option = JSON.stringify({
        uid: uni.getStorageSync('Ztc_B_USER_INFO').tid,
      })
      console.log('看看数据', option)
      uni.navigateTo({
        url: `/pages_common/pages_me/personalInfo/personalInfo?uid=${option}`,
      })
    },

    goFen() {
      uni.navigateTo({
        url: '/pages_common/pages_me/fans/fans',
      })
    },
    goCollection() {
      uni.navigateTo({
        url: '/pages_common/pages_me/collection/collection',
      })
    },
    goMargin() {
      console.log(111)
      uni.navigateTo({
        url: '/pages_common/pages_me/margin/margin',
      })
    },
    //页面跳转
    goPage(url) {
      if (url === '#') {
        uni.showToast({
          title: '敬请期待',
          icon: 'none'
        })
      } else {
        uni.navigateTo({
          url: url,
        })
      }
    },
  },
}
